import defaultConfig from '@/config/env'
import {
	getVisitOpenId,
	imgUpload
} from '@/api/common'
import store from '@/store/index'

// 获取文档滚动高度
function getScrollTop(id, obj) {
	var scrollTop = 0;
	const query = uni.createSelectorQuery().in(obj)
	query.select('#' + id).boundingClientRect(data => {
		scrollTop = data.top - data.height + 30
	}).exec();
	return scrollTop
}

//获取当前可视范围的高度
function getClientHeight() {
	var clientHeight = 0;
	if (document.body.clientHeight && document.documentElement.clientHeight) {
		clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
	} else {
		clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
	}
	return clientHeight;
}
//获取文档完整的高度
function getScrollHeight() {
	return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}

//获取local缓存
function getLocalCache(key) {
	try {
		var cache = uni.getStorageSync(key);
		return cache;
	} catch (e) {
		return '';
	};
}
//设置缓存
function setLocalCache(key, value) {
	try {
		uni.setStorageSync(key, value);
	} catch (e) {};
}
//删除缓存
function removeLocalCache(key) {
	try {
		uni.removeStorageSync(key);
	} catch (e) {};
}

function isWeiXin() {
	// #ifdef H5
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true; // 微信中打开
	} else {
		return false; // 普通浏览器中打开
	}
	// #endif


}


//判断为空
function isBlank(str) {
	if (str == "" || str == "null" || str == "undefined" || str == null || str == undefined) {
		return true;
	} else {
		return false;
	}
}

// 微信分享
function wxShare(item, callback) {
	let wx = require('weixin-js-sdk');
	if (isBlank(item.link)) {
		item.link = window.location.href
	}
	var config = uni.getStorageSync('config')
	var imgUrl = config.logo
	var title = config.title
	var desc = config.shareDesc
	var url = window.location.href.split('/#/')[0] + '/'
	url = encodeURIComponent(url)
	getShare({
		url: url
	}).then(function(res) {
		wx.config({
			debug: false,
			appId: res.appId,
			timestamp: res.timeStamp,
			nonceStr: res.nonceStr,
			signature: res.signature,
			jsApiList: [
				// 所有要调用的 API 都要加到这个列表中
				'onMenuShareTimeline',
				'onMenuShareAppMessage'
			]
		});
		wx.ready(function() {
			wx.onMenuShareAppMessage({
				title: isBlank(item.title) ? res.title : item.title,
				desc: isBlank(item.desc) ? res.desc : item.desc,
				link: item.link,
				imgUrl: isBlank(item.imgUrl) ? res.logo : item.imgUrl,
				success: function(res) {
					if (callback) {
						callback();
					}
				},

			});

			wx.onMenuShareTimeline({
				title: isBlank(item.title) ? res.data.title : item.title + '，' + item.desc,
				link: item.link,
				imgUrl: isBlank(item.imgUrl) ? res.data.logo : item.imgUrl,
				success: function(res) {
					if (callback) {
						callback();
					}
				}
			});
		});
	})
}
// 默认微信分享
function defaultWxShare() {
	let wx = require('weixin-js-sdk');
	getShare({
		url: window.location.href
	}).then(function(res) {
		wx.config({
			debug: false,
			appId: res.data.appid,
			timestamp: res.data.timestamp,
			nonceStr: res.data.noncestr,
			signature: res.data.signature,
			jsApiList: [
				// 所有要调用的 API 都要加到这个列表中
				'onMenuShareTimeline',
				'onMenuShareAppMessage'
			]
		});
		wx.ready(function() {
			wx.onMenuShareAppMessage({
				title: '认识企业极',
				desc: '一个专为未来新商业势力搭建的数字商业科技服务平台',
				link: 'https://m.v-digit.com/pages/login/introduce',
				imgUrl: res.data.logo,
				success: function(res) {}
			});

			wx.onMenuShareTimeline({
				title: '认识企业极 | 一个专为未来新商业势力搭建的数字商业科技服务平台',
				link: 'https://m.v-digit.com/pages/login/introduce',
				imgUrl: res.data.logo,
				success: function(res) {}
			});
		});
	})
}
//微信授权
function getUserinfo() {
	// removeLocalCache('openid')
	if (isBlank(getLocalCache('openid'))) {
		let link = window.location.href;
		var code = getQueryVariable('code');
		if (code) {
			getVisitOpenId({
				code: code
			}).then((res) => {
				if (res.openid) {
					setLocalCache("openid", res.openid);
					store.commit('SET_OPENID', res.openid)
					// try {
					// 	openidLogin(res.data).then((res) => {
					// 		if (res.data) {
					// 			try {
					// 				setLocalCache("uid", res.data.userId);
					// 				setLocalCache("token", res.data.token);
					// 				setLocalCache("vip", res.data.vip);
					// 			} catch (e) {};
					// 		}
					// 		var preUrl = getLocalCache("url")
					// 		removeLocalCache('url')
					// 		var curUrl = window.location.pathname + window.location.search
					// 		if (curUrl.indexOf(preUrl) >= 0) {
					// 			return false
					// 		} else {
					// 			window.location.href = config.baseUrl + preUrl.substring(1)
					// 		}
					// 	});
					// } catch (e) {}
				} else {
					// getUserinfo()
				}
			});
		} else {
			getUrl()
			let appid = defaultConfig[defaultConfig.mchType].wxAppid;
			let uri = encodeURIComponent(link);
			let authURL =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
			console.log(authURL)
			window.location.href = authURL;
		}
		return false
	}
}

function getUrl() {
	var url = window.location.pathname
	var param = window.location.search
	if (url == '/') {
		url = '/pages/index/index'
	}
	setLocalCache('url', url + param)
	return url + param
}
//用户自动登录
function autoLogin(obj) {
	// var openid = getLocalCache('openid')
	// if (isBlank(openid)) {
	// 	obj.$isResolve();
	// 	getUserinfo()
	// 	return false
	// }
	// openidLogin(openid).then((res) => {
	// 	if (res.data) {
	// 		try {
	// 			setLocalCache("uid", res.data.userId)
	// 			setLocalCache("token", res.data.token)
	// 			setLocalCache("vip", res.data.vip)
	// 			setTimeout(function() {
	// 				obj.$isResolve();
	// 			}, 200)
	// 		} catch (e) {
	// 			obj.$isResolve();
	// 		};
	// 	} else {
	// 		obj.$isResolve();
	// 	}
	// });
}
//微信支付
function wxPay(data, callback, failback) {
	var wx = require('weixin-js-sdk');
	var that = this;
	wx.config({
		debug: false, //这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
		appId: data.appId,
		timestamp: data.timeStamp,
		nonceStr: data.nonceStr,
		signature: data.paySign,
		jsApiList: ["chooseWXPay"],
	});
	wx.ready(function() {
		wx.chooseWXPay({
			appId: data.appId,
			timestamp: data
				.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
			nonceStr: data.nonceStr, // 支付签名随机串，不长于 32
			package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
			signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
			paySign: data.paySign, // 支付签名
			success: function(res) {
				if (callback) {
					callback();
				}
			},
			cancel: function(res) {
				if (failback) {
					failback();
				}
			},
			fail: function(res) {
				if (failback) {
					failback();
				}
			},
		});
	});
}

//获取href参数
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return '';
}

export function pathToBase64(path) {
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			if (typeof FileReader === 'function') {
				var xhr = new XMLHttpRequest()
				xhr.open('GET', path, true)
				xhr.responseType = 'blob'
				xhr.onload = function() {
					if (this.status === 200) {
						let fileReader = new FileReader()
						fileReader.onload = function(e) {
							resolve(e.target.result)
						}
						fileReader.onerror = reject
						fileReader.readAsDataURL(this.response)
					}
				}
				xhr.onerror = reject
				xhr.send()
				return
			}
			var canvas = document.createElement('canvas')
			var c2x = canvas.getContext('2d')
			var img = new Image
			img.onload = function() {
				canvas.width = img.width
				canvas.height = img.height
				c2x.drawImage(img, 0, 0)
				resolve(canvas.toDataURL())
				canvas.height = canvas.width = 0
			}
			img.onerror = reject
			img.src = path
			return
		}
		if (typeof plus === 'object') {
			plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader()
					fileReader.onload = function(data) {
						resolve(data.target.result)
					}
					fileReader.onerror = function(error) {
						reject(error)
					}
					fileReader.readAsDataURL(file)
				}, function(error) {
					reject(error)
				})
			}, function(error) {
				reject(error)
			})
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			wx.getFileSystemManager().readFile({
				filePath: path,
				encoding: 'base64',
				success: function(res) {
					resolve('data:image/png;base64,' + res.data)
				},
				fail: function(error) {
					reject(error)
				}
			})
			return
		}
		reject(new Error('not support'))
	})
}

/** 
 * 获取字符串URL参数
 * @param {String} url 原字符串URL
 * @param {String} name 要获取的参数名称
 */
function getUrlCode(url, name) {
	let _url = '?' + url
	return (
		decodeURIComponent(
			(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
				_url
			) || [, ""])[1].replace(/\+/g, "%20")
		) || null
	);
}

/** 
 * 获取字符串URL参数
 * @param {String} url 原字符串URL
 * @param {String} name 要获取的参数名称
 */
function getUrlCode1(url, name) {
	let _url = '?' + url
	return (
		decodeURIComponent(
			(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
				_url
			) || [, ""])
		) || null
	);
}

function getQueryParams(path) {
	if (path.split('?').length <= 1) return null;
	return path
		.split('?')[1] // 去掉 ?
		.split('&') // 按 & 拆分
		.reduce((params, param) => {
			const [key, value] = param.split('=');
			params[decodeURIComponent(key)] = decodeURIComponent(value || '');
			return params;
		}, {});
}


function isIos() {
	var u = navigator.userAgent;
	var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	return isiOS;
}

// 字符串超过目标字节时增加省略号
function getByteLen(str, num) {
	let len = 0;
	let arr = [];
	for (let i = 0; i < str.length; i++) {
		str.charCodeAt(i) < 256 ? (len += 1) : (len += 2)
		arr.push(str[i])
		if (len >= num) break;
	}
	return arr.join('') + '...';
}

function formatRichText(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
	return newContent;

}
// 获取当前年月日
function getdate(target) {
	let myDate = target ? new Date(target) : new Date()
	let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
	let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
	let myToday = myDate.getDate(); //获取当前日(1-31)
	myMonth = myMonth > 9 ? myMonth : '0' + myMonth
	myToday = myToday > 9 ? myToday : '0' + myToday
	let nowDate = `${myYear}-${myMonth}-${myToday}`
	return nowDate
}
// 当前时间与指定时间的间隔时间
function intervalTime(time) {
	let nowTime = +new Date(); // 返回的是当前时间总的毫秒数
	let inputTime = +new Date(time); // 返回的是用户输入时间总的毫秒数
	let times = (nowTime - inputTime) / 1000; // times是剩余时间总的秒数 
	let d = parseInt(times / 60 / 60 / 24); // 天
	let h = parseInt(times / 60 / 60 % 24); //时
	return {
		time: d > 0 ? `${d}天${h}小时` : `${h}小时`,
		day: d
	}
}
// 设置结束时间
function setEndDate(target) {
	let today = new Date();
	//计算目标时间与当前时间间隔(毫秒数)
	var timeold = target - today.getTime(); //getTime 方法返回一个整数值，这个整数代表了从 1970 年 1 月 1 日开始计算到 Date 对象中的时间之间的毫秒数。
	//计算目标时间与当前时间的秒数
	var sectimeold = timeold / 1000;
	//计算目标时间与当前时间的秒数(整数)
	var secondsold = Math.floor(sectimeold);
	//计算一天的秒数
	var msPerDay = 24 * 60 * 60 * 1000;
	//得到剩余天数
	var e_daysold = timeold / msPerDay;
	//得到剩余天数(整数)
	var daysold = Math.floor(e_daysold);
	//得到剩余天数以外的小时数
	var e_hrsold = (e_daysold - daysold) * 24;
	//得到剩余天数以外的小时数(整数)
	var hrsold = Math.floor(e_hrsold);
	//得到尾剩余分数
	var e_minsold = (e_hrsold - hrsold) * 60;
	//得到尾剩余分数(整数)
	var minsold = Math.floor((e_hrsold - hrsold) * 60);
	//得到尾剩余秒数(整数)
	var seconds = Math.floor((e_minsold - minsold) * 60);
	let currentTiem = new Date().getTime();
	let deadlineTiem = new Date(target).getTime();
	if (currentTiem >= deadlineTiem) {
		return "已结束";
	} else {
		//小时取两位,不足补0
		if (hrsold < 10) {
			hrsold = "0" + hrsold;
		}
		//分数取两位,不足补0
		if (minsold < 10) {
			minsold = "0" + minsold;
		}
		//秒数取两位,不足补0
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
	}
	return `${parseInt(e_daysold)}天 ${hrsold}:${minsold}:${seconds}`;
}

// 一维数组转二维数组
function twoArray(arr, num) {
	let newArr = []
	const total = Math.ceil(arr.length / num)
	for (let i = 0; i < total; i++) {
		let a = arr.slice(i * num, (i + 1) * num)
		newArr.push(a)
	}
	return newArr
}

/** 
 * 页面跳转方法
 * @param {Object} obj
 * @param {String} obj.url 跳转地址
 */
function navigateTo(obj) {
	let url = obj.url;
	let pages = getCurrentPages();
	let is_link = 1;
	let iindex = '';
	for (let i = 0; i < pages.length; i++) {
		let is_url = "/" + pages[i].route
		if (url == is_url) {
			is_link++;
			iindex = i;
		}
	}

	if (is_link == 2) {
		uni.navigateBack({
			delta: pages.length - iindex - 1
		})
	} else {
		if (pages.length < 10) {
			uni.navigateTo({
				url: url
			})
		} else {
			uni.redirectTo({
				url: url
			})
		}
	}
}

/** 
 * 节流函数
 * @param {Function} fn 需要运行的函数
 * @param {Number} wait 节流间隔
 */
let timeout = null

function debounce(fn, wait) {
	if (timeout !== null) clearTimeout(timeout)
	timeout = setTimeout(fn, wait)
}

/**
 * 返回上一级页面 
 */
function toBack() {
	if (getCurrentPages().length === 1) {
		uni.reLaunch({
			url: '/pages/index/index/index'
		})
	} else {
		uni.navigateBack({
			delta: 1
		})
	}
}

/** 
 * 活动页面跳转
 * @param {Strign} url 需要跳转的链接
 */
function goActivity(url) {
	// if (url.indexOf('/pages/product/index/index') > -1) { //如果跳转的是商品首页
	// 	let params = url.split('?')[1]
	// 	let classifyCode = '';
	// 	if (params) {
	// 		classifyCode = params.split('=')[1];
	// 	}
	// 	uni.setStorageSync('productParams', {
	// 		classifyCode: classifyCode
	// 	})
	// 	uni.navigateTo({
	// 		url: '/pages/product/index/index'
	// 	})
	// } 
	if (url.indexOf('/pages/service/list/index') > -1) { //如果跳转的是服务首页
		let params = url.split('?')[1]
		let typeCode = '';
		if (params) {
			typeCode = params.split('=')[1];
		}
		uni.setStorageSync('serviceParams', {
			typeCode: typeCode
		})
		uni.switchTab({
			url: '/pages/service/list/index'
		})
	} else {
		navigateTo({
			url
		})
	}
}


/*  
功能 去重
参数 arr 原数组
	key 对object中的某个字段进行去重
*/
function unique(arr, key = null) {
	for (let i = 0; i < arr.length; i++) {
		for (let j = i + 1; j < arr.length; j++) {
			if (key) {
				if (arr[i][key] === arr[j][key]) {
					arr.splice(j, 1); // 移除重复元素
					j--; // 修正下标
				}
			} else {
				if (arr[i] === arr[j]) {
					arr.splice(j, 1); // 移除重复元素
					j--; // 修正下标
				}
			}
		}
	}
	return arr;
};
// 冒泡排序 从大到小
function bubbleSort(arr, field) {
	for (let i = 0; i < arr.length - 1; i += 1) {
		//通过 this.length 次把第一位放到最后,完成排序
		//-i是因为最后的位置是会动态改变的，当完成一次后,最后一位会变成倒数第二位 
		for (let j = 0; j < arr.length - 1 - i; j += 1) {
			if (arr[j][field] < arr[j + 1][field]) {
				const temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	return arr
}

/**
 * 判断是否已经登录 
 */
function isLogin(showToast = true) {
	var token = uni.getStorageSync('token')
	if (!token) {
		if (showToast) {
			// uni.showToast({
			// 	title: "没有登录，请登录",
			// 	icon: "none"
			// })
			this.$refs?.loginModal?.open()
			// setTimeout(() => {
			// 	uni.navigateTo({
			// 		url: "/pages/login/login"
			// 	})
			// }, 500)
		}
		return false
	}
	return true
}

function fuseTeamData(data) {
	var pet_team = uni.getStorageSync('pet_team')
	let _data = {}
	if (pet_team.teamId != -1) {
		_data.teamId = pet_team.teamId
		_data.teamName = pet_team.teamName
		return {
			..._data,
			...data
		}
	}
	return data
}

/** 
 * 阿拉伯数字转中文数字
 * @param {Number} num 阿拉伯数字
 * @returns {String} 中文数字
 */
function numberToChinese(num) {
	const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	const chineseUnits = ['', '十', '百', '千', '万', '十', '百', '千', '亿'];

	if (num === 0) return chineseNumbers[0];

	let str = '';
	let unitIndex = 0;

	while (num > 0) {
		const digit = num % 10;
		if (digit !== 0) {
			str = chineseNumbers[digit] + chineseUnits[unitIndex] + str;
		} else {
			// 避免重复的“零”
			if (str.charAt(0) !== chineseNumbers[0]) {
				str = chineseNumbers[digit] + str;
			}
		}
		num = Math.floor(num / 10);
		unitIndex++;
	}

	// 处理“一十”开头的特殊情况
	if (str.startsWith('一十')) {
		str = str.substring(1);
	}

	return str;
}
export default {
	getScrollTop: getScrollTop,
	getClientHeight: getClientHeight,
	getScrollHeight: getScrollHeight,
	getLocalCache: getLocalCache,
	setLocalCache: setLocalCache,
	removeLocalCache: removeLocalCache,
	isIos: isIos,
	getByteLen,
	formatRichText,
	setEndDate,
	getdate,
	twoArray,
	navigateTo,
	debounce,
	toBack,
	goActivity,
	intervalTime,
	unique,
	bubbleSort,
	isLogin,
	getUrlCode,
	getUrlCode1,
	isWeiXin,
	wxShare,
	defaultWxShare,
	getUserinfo,
	autoLogin,
	fuseTeamData,
	getQueryParams,
	numberToChinese
};